package com.fang.transfer.file.common;

import com.fang.transfer.file.ThreadContext;
import com.fang.transfer.file.common.code.ClientSendCode;
import com.fang.transfer.file.listener.RequestListenerManagement;
import com.fang.transfer.file.service.UserService;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.net.SocketAddress;

/**
 * @author adsf
 */
@Service
@Scope("prototype")
@Slf4j
public class MyChannelInboundHandler extends ChannelInboundHandlerAdapter {
    @Autowired
    private ChannelManagement channelManagement;
    @Autowired
    private UserService userService;
    @Autowired
    private RequestListenerManagement requestListenerManagement;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String info = (String) msg;
        String code = info.substring(0, 3);
        String json = info.substring(3);

        RequestListener listener = requestListenerManagement.getByCode(code);
        Object param  = listener.jsonToParam(json);
        try {
            ThreadContext.setChannelHandlerContext(ctx);
            listener.handle(param);
        } catch (Exception ex) {
            throw ex;
        } finally {
            ThreadContext.removeChannelHandlerContext();
        }
        super.channelRead(ctx, msg);
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        SocketAddress remoteAddress = ctx.channel().remoteAddress();
        String id = ctx.channel().id().toString();
        log.info("连接建立 remoteAddress:{}  id:{} ", remoteAddress, id);
        channelManagement.add(id, ctx);
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        SocketAddress remoteAddress = ctx.channel().remoteAddress();
        log.info("channelInactive:{}", remoteAddress);
        channelManagement.remove(ctx);
        String id = ctx.channel().id().toString();
        this.userService.logout(id);
        super.channelActive(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        SocketAddress remoteAddress = ctx.channel().remoteAddress();
        log.info("exceptionCaught:{}", remoteAddress);
        super.exceptionCaught(ctx, cause);
    }
}
